package com.xmxsuperstar.app.gg;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

public class Utils {

	public static String calRate(long currentCompleted, long lastCompleted,
			long currentTime, long lastTime) {
		long time = currentTime - lastTime;
		if (time <= 0) {
			return "   0.0 B/s";
		}
		String[] units = { " B/s", "KB/s", "MB/s", "GB/s", "TB/s" };
		double completed = currentCompleted - lastCompleted;
		int unitsIndex = 0;
		while (completed > 1024) {
			unitsIndex++;
			completed /= 1024;
		}
		return String.format("%1$6.1f", completed / (time / 1000))
				+ units[unitsIndex];
	}

	public static String calETA(long currentCompleted, long lastCompleted,
			long currentTime, long lastTime) {
		long time = currentTime - lastTime;
		if (time <= 0) {
			return String.format("%1$9s", "...");
		}
		long completed = currentCompleted - lastCompleted;
		long rate = completed / time;

		if (rate == 0) {
			return String.format("%1$9s", "...");
		}

		long remainTimeSeconds = ((Statics.getInstance().getFileLength()-currentCompleted) / rate) / 1000;
		if (remainTimeSeconds >= 24 * 60 * 60) {
			return String.format("%1$9s", ">1D");
		}

		long second = remainTimeSeconds % 60;
		long minute = remainTimeSeconds / 60 % 60;
		long hour = remainTimeSeconds / (60 * 60) % 24;

		StringBuilder sb = new StringBuilder(9);
		sb.append(String.format("%1$2d", hour)).append("h");
		sb.append(String.format("%1$2d", minute)).append("m");
		sb.append(String.format("%1$2d", second)).append("s");
		return sb.toString();
	}

	public static String calSize(long bytes) {
		double size = bytes;
		String[] units = { " B", "KB", "MB", "GB", "TB" };
		int unitsIndex = 0;
		while (size > 1024) {
			unitsIndex++;
			size /= 1024;
		}
		return String.format("%1$6.1f", size) + units[unitsIndex];
	}

	public static String decodeURLFileName(URL url) {
		String fileName = new File(url.getFile()).getName();
		String humanFileName = fileName;
		try {
			humanFileName = URLDecoder.decode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return humanFileName;
	}

	public static void setHeader(URLConnection cn) {
		if (cn instanceof HttpURLConnection) {
			cn
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
			cn
					.setRequestProperty("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			cn.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			cn.setRequestProperty("Accept-Encoding", "gzip,deflate");
			cn.setRequestProperty("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			cn.setRequestProperty("Keep-Alive", "115");
			cn.setRequestProperty("Connection", "keep-alive");
		}
	}

}
